package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.FocusUser;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.*;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    //更新用户头像
    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        //1、将图片上传到阿里云oss
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2、调用百度云判断是否包含人脸
        boolean detect = aipFaceTemplate.detect(imageUrl);
        //2.1 如果不包含人脸，抛出异常
        if(!detect) {
            throw new BusinessException(ErrorResult.faceError());
        }else{
            //2.2 包含人脸，调用API更新
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setAvatar(imageUrl);
            userInfoApi.update(userInfo);
        }
    }

    //根据id查寻
    public UserInfoVo findById(Long id) {
        UserInfo userInfo = userInfoApi.findById(id);

        UserInfoVo vo = new UserInfoVo();

        BeanUtils.copyProperties(userInfo,vo); //copy同名同类型的属性

        if(userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }

        return vo;
    }

    //更新
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }

    @DubboReference
    private FriendApi friendApi;

    @DubboReference
    private UserLikeApi userLikeApi;

    @DubboReference
    private FocusUserApi focusUserApi;

    @DubboReference
    private VisitorsApi visitorsApi;

    @Autowired
    private RedisTemplate redisTemplate;

    public Map counts(Long userId) {
        //Dubbo远程调用FriendApi统计查询当前用户的好友
        Long eachLoveCount = friendApi.countFriends(userId);
        //Dubbo远程调用userLikeApi统计查询当前用户喜欢的人
        Long loveCount = userLikeApi.countLovers(userId);
        //Dubbo远程调用focusApi统计查询当前用户喜欢的人
        Long fanCount = focusUserApi.countFans(userId);

        Map map = new HashMap();
        map.put("eachLoveCount",Integer.valueOf(eachLoveCount.toString()));
        map.put("loveCount",Integer.valueOf(loveCount.toString()));
        map.put("fanCount",Integer.valueOf(fanCount.toString()));
        return map;
    }

    public PageResult findFriends(Integer type, Integer page, Integer pagesize, String nickname) {
        //获取当前用户的id
        Long userId = UserHolder.getUserId();

        if (type==1){
            //根据当前用户id调用api查询出互相喜欢的人集合
            List<Friend> friendList = friendApi.findByUserId(userId, page, pagesize);
            //判断集合是否为空
            if (CollUtil.isEmpty(friendList)){
                return new PageResult();
            }
            //根据用户id查询互相喜欢的人总数
            Long counts = friendApi.countFriends(userId);
            //提取用户id，调用userInfoApi查询用户详情
            List<Long> userIds = CollUtil.getFieldValues(friendList, "friendId", Long.class);
            Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(userIds, null);
            //构造vo对象
            List<UserInfoPlusVo> vos = new ArrayList<>();
            for (Friend friend : friendList) {
                UserInfo userInfo = userInfoMap.get(friend.getFriendId());
                if (userInfo != null){
                    UserInfoPlusVo vo = UserInfoPlusVo.initFriend(userInfo,friend);
                    vos.add(vo);
                }
            }
            //构造返回值
            return new PageResult(page,pagesize,counts,vos);
        }else  if (type==2){
            //根据当前用户id调用api查询出用户喜欢的人集合
            List<UserLike> userLikeList = userLikeApi.findByUserId(userId,page,pagesize);
            //判断集合是否为空
            if (CollUtil.isEmpty(userLikeList)){
                return new PageResult();
            }
            //根据用户id查询用户喜欢的人总数
            Long counts = userLikeApi.countLovers(userId);
            //提取用户id，调用userInfoApi查询用户详情
            List<Long> userIds = CollUtil.getFieldValues(userLikeList, "likeUserId", Long.class);
            Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(userIds, null);
            //构造vo对象
            List<UserInfoPlusVo> vos = new ArrayList<>();
            for (UserLike userLike : userLikeList) {
                UserInfo userInfo = userInfoMap.get(userLike.getLikeUserId());
                if (userInfo != null){
                    UserInfoPlusVo vo = UserInfoPlusVo.initUserLike(userInfo,userLike);
                    vos.add(vo);
                }
            }
            //构造返回值
            return new PageResult(page,pagesize,counts,vos);
        }else if (type==3){
            //根据当前用户id调用api查询出粉丝集合
            List<FocusUser> fansList = focusUserApi.findByUserId(userId,page,pagesize);
            //判断集合是否为空
            if (CollUtil.isEmpty(fansList)){
                return new PageResult();
            }
            //根据用户id查询用户喜欢的人总数
            Long counts = focusUserApi.countFans(userId);
            //提取用户id，调用userInfoApi查询用户详情
            List<Long> userIds = CollUtil.getFieldValues(fansList, "userId", Long.class);
            Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(userIds, null);
            //构造vo对象
            List<UserInfoPlusVo> vos = new ArrayList<>();
            for (FocusUser focusUser : fansList) {
                UserInfo userInfo = userInfoMap.get(focusUser.getUserId());
                if (userInfo != null){
                    UserInfoPlusVo vo = UserInfoPlusVo.initFocusUser(userInfo,focusUser);
                    vos.add(vo);
                }
            }
            //构造返回值
            return new PageResult(page,pagesize,counts,vos);
        }else if (type==4){
            //1、查询访问时间
            String key = Constants.VISITORS_USER;
            String hashKey = String.valueOf(UserHolder.getUserId());
            String value = (String) redisTemplate.opsForHash().get(key, hashKey);
            Long date = StringUtils.isEmpty(value) ? null:Long.valueOf(value);
            //2、调用API查询数据列表 List<Visitors>
            List<Visitors> list =  visitorsApi.queryMyVisitors(date,UserHolder.getUserId());
            if(CollUtil.isEmpty(list)) {
                return new PageResult();
            }
            //3、提取用户的id
            List<Long> userIds = CollUtil.getFieldValues(list, "visitorUserId", Long.class);
            //4、查看用户详情
            Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
            //5、构造返回
            List<UserInfoPlusVo> vos = new ArrayList<>();
            for (Visitors visitors : list) {
                UserInfo userInfo = map.get(visitors.getVisitorUserId());
                if(userInfo != null) {
                    UserInfoPlusVo vo = UserInfoPlusVo.initVistors(userInfo, visitors);
                    vos.add(vo);
                }
            }
            return new PageResult(page,pagesize,0l,vos);
        }
        return null;
    }

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    public void likeById(Long uid) {
        //根据当前用户id调用api查询出用户详情
        UserInfo userInfo= userInfoApi.findById(uid);
        //判断集合是否为空
        if (userInfo == null){
             throw new BusinessException(ErrorResult.error());
        }else {
            //构造vo对象
            UserInfoPlusVo vo = UserInfoPlusVo.init(userInfo);
            vo.setAlreadyLove(true);
            //删除focus_user表中数据
            Long followUserId = UserHolder.getUserId();
            focusUserApi.deleteById(uid,followUserId);
            //friend表中添加互相喜欢的两条数据
            friendApi.save(uid,followUserId);
            //user_like表中添加互相喜欢的两条数据
            userLikeApi.saveOrUpdate(uid,followUserId,true);
            userLikeApi.saveOrUpdate(followUserId,uid,true);

            huanXinTemplate.addContact("hx"+uid,"hx"+followUserId);
        }
    }

    public void dislikeById(Long uid) {
        //根据当前用户id调用api查询出用户详情
        UserInfo userInfo= userInfoApi.findById(uid);
        //判断集合是否为空
        if (userInfo == null){
            throw new BusinessException(ErrorResult.error());
        }else {
            //构造vo对象
            UserInfoPlusVo vo = UserInfoPlusVo.init(userInfo);
            vo.setAlreadyLove(false);
            //删除user_like表中数据
            userLikeApi.deleteById(uid);
        }
    }
}
